<template>
  <view>
    <!-- H5端用div，小程序端用map组件 -->
    <div v-if="isH5" :id="containerId" :style="containerStyle"></div>
    <map
      v-else
      :longitude="center[0]"
      :latitude="center[1]"
      :scale="zoom"
      :style="containerStyle"
      :markers="markers"
      show-location
    />
  </view>
</template>

<script>
const DEFAULT_CENTER = [115.858197, 28.682892]; // 南昌

export default {
  name: "UniAmap",
  props: {
    center: {
      type: Array,
      default: () => DEFAULT_CENTER,
    },
    zoom: {
      type: Number,
      default: 13,
    },
    markers: {
      type: Array,
      default: () => [],
    },
    containerStyle: {
      type: String,
      default: "width:100%;height:10rem;margin-bottom:1rem;",
    },
  },
  data() {
    return {
      isH5: process.env.UNI_PLATFORM === "h5",
      map: null,
      containerId: "amap-container-" + Math.random().toString(36).substr(2, 8),
    };
  },
  watch: {
    center: {
      handler(newCenter) {
        console.log("地图中心点变化:", newCenter);
        if (this.map && this.isH5) {
          this.map.setCenter(newCenter);
        }
      },
      deep: true,
    },
    markers: {
      handler(newMarkers) {
        console.log("地图标记变化:", newMarkers);
        if (this.map && this.isH5) {
          this.updateMarkers(newMarkers);
        }
      },
      deep: true,
    },
    zoom(newZoom) {
      console.log("地图缩放级别变化:", newZoom);
      if (this.map && this.isH5) {
        this.map.setZoom(newZoom);
      }
    },
  },
  mounted() {
    if (this.isH5) {
      this.initAMap();
    }
    // 小程序端无需手动初始化
  },
  methods: {
    initAMap() {
      // 动态加载高德地图JS
      if (!window.AMap) {
        const script = document.createElement("script");
        script.src = "https://webapi.amap.com/maps?v=2.0&key=215af0c59d107e56c394d45fe1ba4d04";
        script.onload = this.createMap;
        document.head.appendChild(script);
      } else {
        this.createMap();
      }
    },
    createMap() {
      this.map = new window.AMap.Map(this.containerId, {
        center: this.center,
        zoom: this.zoom,
        resizeEnable: true,
      });

      // 初始化标记
      this.updateMarkers(this.markers);
    },
    updateMarkers(markers) {
      // 清除现有标记
      if (this.map) {
        this.map.clearMap();
      }

      let firstMarker = null;
      let firstInfoWindow = null;

      // 渲染标记
      if (markers && markers.length) {
        const markerData = markers[0];
        // 确保 position 是数字数组
        let pos = markerData.position;
        if (Array.isArray(pos)) {
          pos = [Number(pos[0]), Number(pos[1])];
        }
        const amapMarker = new window.AMap.Marker({
          position: markerData.position,
          map: this.map,
          title: markerData.title || "",
          icon: markerData.icon || "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/118709c8b02c4b1191ebbff197cb20ae.png",
          offset: new window.AMap.Pixel(-16, -20),
        });
        // 支持点击弹窗
        if (markerData.info) {
          // markerData.info 可为对象，包含图片、标题、价格、地址、电话、详情等
          const info = markerData.info;
          // 构建内容
          const infoHtml = `
            <div style="min-width:220px;max-width:300px;">
              <div class="fmTitle">${info.title || ""}</div>
              <div style='height:54px;margin:8px 0;'>
                <img class="imgFm" src='${info.coverImage || ""}' />
                <div style='font-size:13px;'>
                  <span id="go-nav-btn" style="color:#1890ff;cursor:pointer;">点击导航去: </span>
                  <div>${info.address || ""}</div>
                </div>
              </div>
            </div>
          `;
          const infoWindow = new window.AMap.InfoWindow({
            content: infoHtml,
            offset: new window.AMap.Pixel(0, -30),
          });
          amapMarker.on("click", () => {
            infoWindow.open(this.map, amapMarker.getPosition());
            setTimeout(() => {
              const navBtn = document.getElementById("go-nav-btn");
              if (navBtn) {
                navBtn.onclick = () => {
                  console.log(navBtn);
                  // 这里用经纬度跳转高德地图导航
                  const [lng, lat] = markerData.position;
                  // 构造高德地图Web端导航URL
                  const url = `https://uri.amap.com/navigation?to=${lng},${lat},${encodeURIComponent(info.title || "")}&mode=car&policy=1&src=yourAppName`;
                  window.open(url, "_blank");
                };
              }
            }, 100);
          });
          // 记录第一个marker和infoWindow
          firstMarker = amapMarker;
          firstInfoWindow = infoWindow;
        }
      }
      // 循环结束后自动弹出第一个
      if (firstMarker && firstInfoWindow) {
        firstInfoWindow.open(this.map, firstMarker.getPosition());
        const markerData = markers[0];
        const info = markerData.info;
        setTimeout(() => {
          const navBtn = document.getElementById("go-nav-btn");
          if (navBtn) {
            navBtn.onclick = () => {
              console.log(navBtn);
              // 这里用经纬度跳转高德地图导航
              const [lng, lat] = markerData.position;
              // 构造高德地图Web端导航URL
              const url = `https://uri.amap.com/navigation?to=${lng},${lat},${encodeURIComponent(info.title || "")}&mode=car&policy=1&src=yourAppName`;
              window.open(url, "_blank");
            };
          }
        }, 100);
      }
    },
  },
};
</script>

<style scoped>
/* 你可以自定义样式 */
:deep(.imgFm) {
  width: 60px;
  height: 54px;
  object-fit: cover;
  float: left;
  margin-right: 8px;
}
:deep(.fmTitle) {
  font-size: 16px;
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 14rem;
}
</style>
